package cn.yhsx.jenkins.plugins.rotator;

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import net.sf.json.JSONObject;

/**
 * when build is success,auto save config file
 *
 * @author slf
 * @since 2025/6/13 20:22
 **/
@Extension
public class RotatorListener extends RunListener<Run<?, ?>> {

    @Override
    public void onCompleted(Run run, @NonNull TaskListener listener) {
        if (run.getResult() != null && run.getResult().equals(Result.SUCCESS)) {
            saveConfig(run, listener);
        }
    }

    // 保存配置文件
    public void saveConfig(Run<?, ?> build, TaskListener listener) {
        try {
            RotatorAction action = build.getAction(RotatorAction.class);
            RotatorConfig current = action.getCurrent();
            RotatorConfig last = action.getLast();
            if (last != null && current.getBuildId().equals(last.getLastBuildId())) {//rollback
                listener.getLogger().println("Rollback config:" + current.getCurrentData());
            } else {
                listener.getLogger().println("Save config: " + current.getCurrentData());
                Run<?, ?> lastBuild;
                if (last != null && !current.getCurrent().equals(last.getCurrent()) &&
                        (lastBuild = build.getPreviousSuccessfulBuild()) != null) {//切换目录
                    current.setLastBuildId(lastBuild.getId());
                }
            }
            String content = JSONObject.fromObject(current).toString();
            FilePath statePath = RotatorWrapper.getStateFilePath(build);
            statePath.write(content, "UTF-8");
            FilePath buildStatePath = RotatorWrapper.getBuildStateFilePath(build);
            buildStatePath.copyFrom(statePath);
            buildStatePath.write(content, "UTF-8");
        } catch (Exception e) {
            listener.error("Failed to save Config: " + e.getMessage());
            build.setResult(Result.UNSTABLE);
        }
    }
}
